package com.aho.app.yourfancy;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import android.os.Environment;
import android.util.Log;

public class Logger {
	private static final String OUTPUT_LOG_DIR = Environment.getExternalStorageDirectory().getPath() + "/logdata/";
	//private static final String FILE_NAME = OUTPUT_LOG_DIR + "log.csv";
	
	//----- public method -----//
	public static void write(String fileName, String logData){
		Date now = new Date();
		BufferedWriter buffWriter = null;
		
		String outputFileName = OUTPUT_LOG_DIR + fileName;

		try{
			try{
				mkdir(OUTPUT_LOG_DIR);
			}catch(IOException e){
				e.printStackTrace();
				return;
			}
			FileOutputStream file = new FileOutputStream(outputFileName, true);
			buffWriter = new BufferedWriter(new OutputStreamWriter(file, "UTF-8"));
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}
		
		try{
			buffWriter.append((now.getYear()+1900)+"/"+(now.getMonth()+1)+"/"+now.getDate()
					+","+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+","+logData+"\n");
			Log.e("log",(now.getYear()+1900)+"/"+(now.getMonth()+1)+"/"+now.getDate()
					+","+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+","+logData+"\n");
		}catch(IOException e){
			e.printStackTrace();
		}
		
		try{
			buffWriter.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		buffWriter = null;
	}

	public static boolean mkdir(File dir) throws IOException{
		if(!dir.exists()){
			if(!dir.mkdirs()){
				throw new IOException("File.mkdirs() failed.");
			}
			return true;
		} else if(!dir.isDirectory()){
			throw new IOException("Cannot create path. " + dir.toString() + " already exists and is not a directory.");
		} else{
			return false;
		}
	}

	public static boolean mkdir(String dir) throws IOException{
		return mkdir(new File(dir));
	}
}
